package com.situ.mall.controller;


import com.situ.mall.pojo.entity.Cart;
import com.situ.mall.pojo.vo.CartVO;
import com.situ.mall.service.ICartService;
import com.situ.mall.util.JwtUtil;
import com.situ.mall.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Gao
 * @since 2025-10-15
 */
@RestController
@RequestMapping("/order/cart")
public class CartController {
    @Autowired
    private ICartService cartService;

    @GetMapping("/selectByIds")
    public Result<List<CartVO>> selectByIds(Integer[] cartIds) {
        List<CartVO> list = cartService.selectByIds(cartIds);
        return Result.ok(list);
    }

    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Integer id) {
        cartService.removeById(id);
        return Result.ok("删除成功");
    }

    @PutMapping("/update")
    public Result update(@RequestBody Cart cart) {
        cartService.updateById(cart);
        return Result.ok("更新成功");
    }

    @GetMapping("/list")
    public Result<List<CartVO>> list(@RequestHeader(name = "Authorization")String token) {
        Map<String, Object> tokenMap = JwtUtil.parseToken(token);
        Integer userId = (Integer) tokenMap.get("id");
        List<CartVO> list = cartService.selectByUserId(userId);
        return Result.ok(list);
    }

    @PostMapping("/add/{productId}")
    public Result add(@PathVariable Integer productId, @RequestHeader(name = "Authorization")String token) {
        Map<String, Object> tokenMap = JwtUtil.parseToken(token);
        Integer userId = (Integer) tokenMap.get("id");
        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setProductId(productId);
        cart.setCount(1);
        cartService.add(cart);
        return Result.ok("加入购物车成功");
    }

}

